package com.rongxun.hbwallet.ui.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.support.annotation.NonNull;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.rongxun.base.MvpFragment;
import com.rongxun.hbwallet.R;
import com.rongxun.hbwallet.constants.HttpConstants;
import com.rongxun.hbwallet.constants.IntentKey;
import com.rongxun.hbwallet.constants.SPKey;
import com.rongxun.hbwallet.jsinterface.JsInteration;
import com.rongxun.hbwallet.model.bean.H5UserInfo;
import com.rongxun.hbwallet.model.bean.User;
import com.rongxun.hbwallet.mvp.contract.IExcavate;
import com.rongxun.hbwallet.mvp.presenter.ExcavatePresenter;
import com.rongxun.hbwallet.ui.activities.ExcavateActivity;
import com.rongxun.hbwallet.ui.activities.LoginActivity;
import com.rongxun.hbwallet.ui.activities.WalletManagerActivity;
import com.rongxun.hbwallet.ui.activities.WebActivity;
import com.rongxun.utils.ActivityUtils;
import com.rongxun.utils.FlyLog;
import com.rongxun.utils.JsonUtils;
import com.rongxun.utils.PreferenceUtils;
import com.rongxun.utils.StatusBarUtil;
import com.rongxun.utils.wallet.ETHWallet;
import com.rongxun.utils.wallet.WalletDaoUtils;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.Unbinder;
import wendu.webviewjavascriptbridge.WVJBWebView;

/**
 * 创建者     庄丰泽
 * 创建时间   2018/5/21 10:28
 * 描述  挖宝
 */

public class ExcavateFragment extends MvpFragment<IExcavate.IView, ExcavatePresenter> implements IExcavate.IView, View.OnKeyListener {
    @BindView(R.id.shop_wv)
    WVJBWebView mWebView;
    @BindView(R.id.toolbar_title)
    TextView    mToolbarTitle;
    @BindView(R.id.toolbar)
    Toolbar     mToolbar;
    @BindView(R.id.shop_prb)
    ProgressBar mShopPrb;
    @BindView(R.id.toolbar_right_text)
    TextView    mRight;
    Unbinder unbinder;

    private String url = HttpConstants.WEB_ADDRESS.EXCAVATE_URL;
    //    private String url = "http://www.saleseasy.cn/candytest/index.html#/mall";


    @Override
    public void showLoading(boolean isShow) {

    }

    @Override
    public void showError(String msg, String errorCode) {
    }

    @Override
    public void checkPermissionsSuccessful(String... permissions) {

    }

    @Override
    public void release() {
        if (mWebView != null) {
            mWebView.freeMemory();
            mWebView.clearCache(true);
            mWebView.clearHistory();
            mWebView.clearFormData();
            mWebView.destroy();
        }

    }

    @NonNull
    @Override
    public ExcavatePresenter createPresenter() {
        return new ExcavatePresenter(this);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_web;
    }

    @Override
    protected void init() {
        StatusBarUtil.setToolBarPaddingTop(mToolbar, activity);
        mToolbarTitle.setText(getString(R.string.excavate));
        mRight.setText(activity.getString(R.string.detail));
        mRight.setVisibility(View.VISIBLE);
        initWebView();
    }

    private void initWebView() {


        mWebView.setWebViewClient(new WebViewClient() {

            @Override
            public void onLoadResource(WebView view, String url) {
                FlyLog.i("onLoadResource" + url);
                super.onLoadResource(view, url);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                FlyLog.i("shouldOverrideUrlLoading" + url);

                return false;
            }


            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                FlyLog.i("onPageStarted" + url);
                super.onPageStarted(view, url, favicon);


                mShopPrb.setVisibility(View.VISIBLE);
            }


            @Override
            public void onPageFinished(WebView view, String url) {
                FlyLog.i("onPageFinished" + url);
                super.onPageFinished(view, url);
                mShopPrb.setVisibility(View.GONE);
                callEvaluateJavascript(mWebView);
            }
        });


        mWebView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                if (title != null) {
                    mToolbarTitle.setText(title);
                }
            }

            //加载进度
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                mShopPrb.setProgress(newProgress);

            }


            @Override
            public void onRequestFocus(WebView view) {
                super.onRequestFocus(view);
            }

            @Override
            public void onCloseWindow(WebView window) {
                super.onCloseWindow(window);
            }

            @Override
            public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
                return super.onJsConfirm(view, url, message, result);
            }

        });
        // 得到setting
        WebSettings settings = mWebView.getSettings();

        //支持的语言类型
        settings.setDefaultTextEncodingName("UTF-8");
        //设置可以访问文件
        settings.setAllowFileAccess(true);

        settings.setDomStorageEnabled(true);


        settings.setJavaScriptEnabled(true);//设置JS可用

        mWebView.addJavascriptInterface(new JsInteration(activity), "control");//传递对象进行交互

        settings.setTextZoom(100);
        settings.setUseWideViewPort(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        settings.setLoadWithOverviewMode(true);

        mWebView.setOnKeyListener(this);


    }


    private String getUserInfo() {

        H5UserInfo h5UserInfo = new H5UserInfo();

        h5UserInfo.setToken(PreferenceUtils.getString(SPKey.TOKEN, ""));

        String userJson = PreferenceUtils.getString(SPKey.USER, "");

        User user = JsonUtils.fromJson(userJson, User.class);

        h5UserInfo.setUser(user);

        String toJson = JsonUtils.toJson(h5UserInfo);

        FlyLog.i("toJson" + toJson);
        return toJson;
    }


    private void callEvaluateJavascript(@NonNull WVJBWebView webView) {
        String toJson = getUserInfo();
        webView.callHandler("setH5UserInfo", toJson, (WVJBWebView.WVJBResponseCallback<String>) data -> {

        });
    }

    @Override
    protected void onLazyLoadOnce() {
        super.onLazyLoadOnce();
        mWebView.loadUrl(url);
        mWebView.registerHandler("setNativeTitle", (WVJBWebView.WVJBHandler<String, String>) (s, wvjbResponseCallback) ->
                mToolbarTitle.setText(s));

        mWebView.registerHandler("getNativeUserInfo", (WVJBWebView.WVJBHandler<String, String>) (s, wvjbResponseCallback) ->
                wvjbResponseCallback.onResult(getUserInfo()));

        mWebView.registerHandler("startExcavate", (WVJBWebView.WVJBHandler<String, String>) (s, wvjbResponseCallback) -> {

            String userId = PreferenceUtils.getString(SPKey.USERID, "0");
            if (Integer.parseInt(userId) == 0) {
                ActivityUtils.startActivityWithAnimotion(activity, new Intent(activity, LoginActivity.class));
                return;
            }
            ETHWallet ethWallet = WalletDaoUtils.checkRepeatByUserId(userId);
            if (ethWallet == null) {
                ActivityUtils.startActivityWithAnimotion(activity, new Intent(activity, WalletManagerActivity.class));
                return;
            }

            ActivityUtils.startActivityWithAnimotion(activity, new Intent(activity, ExcavateActivity.class).putExtra(IntentKey.ETH_WALLET, ethWallet));
        });

        mWebView.registerHandler("tokenExpired", (WVJBWebView.WVJBHandler<String, String>) (s, wvjbResponseCallback) ->
                ActivityUtils.startActivityWithAnimotionBottomToTop(activity, new Intent(activity, LoginActivity.class)));
    }

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
            mWebView.goBack();
            return true;
        }
        return false;
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick(R.id.toolbar_right_text)
    public void onViewClicked() {
        String userId = PreferenceUtils.getString(SPKey.USERID, "0");
        if (Integer.parseInt(userId) == 0) {
            ActivityUtils.startActivityWithAnimotion(activity, new Intent(activity, LoginActivity.class));
            return;
        }
        ETHWallet ethWallet = WalletDaoUtils.checkRepeatByUserId(userId);
        if (ethWallet == null) {
            ActivityUtils.startActivityWithAnimotion(activity, new Intent(activity, WalletManagerActivity.class));
            return;
        }
        ActivityUtils.startActivityWithAnimotion(activity, new Intent(activity, WebActivity.class)
                .putExtra(IntentKey.WEB_URL,HttpConstants.WEB_ADDRESS.TREASUREDETAIL_URL));

    }
}